package cn.zxyh.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import cn.zxyh.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import cn.zxyh.pojo.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
	@Autowired
	LoginService loginService;
	@Autowired
	RedisTemplate redisTemplate;
	@PostMapping("/login")
	@ResponseBody
	public Map<String,Object> login(@RequestBody Map<String,String> loginMap){
		String username=loginMap.get("username");
		String password=loginMap.get("password");
		User user = loginService.login(username,password);
		Map<String,Object> map = new HashMap<>();
		if(user == null){
			map.put("code",1);
			map.put("msg","用户名或密码错误");
			return map;
		}else {
			map.put("code",0);
			String token = UUID.randomUUID().toString();
			Map<String,Object> map1 = new HashMap<>();
			map1.put("access_token",token);
			map.put("data",map1);
			redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES);
			return map;
		}
	}

	@PostMapping("/regist")
	@ResponseBody
	public Map<String, Object> regist(@RequestBody Map<String,String> userMap) {
		Map<String, Object> map = new HashMap<>();
		String username = userMap.get("username");
		String password = userMap.get("password");
		String cardNumber = userMap.get("cardNumber");
		String payPassword = userMap.get("payPassword");
		int result = loginService.regist(username, password, cardNumber,payPassword);
		if(result == 0)
			map.put("code",0);
		else {
			map.put("code", 1);
			map.put("msg","注册失败");
		}

		return map;

	}
}
